/**
 * @class   wosh::gui::WidgetUser
 * @brief   
 *          
 *          
 *
 ****************************************************************************
 * @version $Id: WidgetUser.h 2184 2010-03-20 13:19:23Z alex $
 * @author  Alessandro Polo
 ****************************************************************************/
/* Copyright (c) 2007-2010, WOSH - Wide Open Smart Home 
 * by Alessandro Polo - OpenSmartHome.com
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the OpenSmartHome.com WOSH nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY Alessandro Polo ''AS IS'' AND ANY
 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL Alessandro Polo BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 ****************************************************************************/

#ifndef __WOSH_Gui_WidgetUser_H__
 #define __WOSH_Gui_WidgetUser_H__

 #include <core/URI.h>
 #include <core/UserManager.h>
 #include <core/MethodsDef.h>
 #include <core/Request.h>
 #include <core/Response.h>
 #include <core/Table.h>

 #include <framework/gui/IWidget.h>
 #include <framework/gui/WoshTableModel.h>
 #include <framework/gui/WidgetProperties.h>

 #include "ui_WidgetUser.h"
 #include <QMenu>
 #include <QMessageBox>
 #include <QHeaderView>


namespace wosh {
 namespace gui {


class WidgetUser :  public QWidget, public IWidget  {

	Q_OBJECT

	public:

		WidgetUser(QWidget *parent = 0) : QWidget(parent), IWidget()
		 {
			this->m_ui = new Ui::WidgetUser();
			this->m_ui->setupUi(this);

			buildMenus();


			this->m_ui->tableViewComm->setContextMenuPolicy(Qt::CustomContextMenu);
			connect(this->m_ui->tableViewComm, SIGNAL(updated()), this->m_ui->wUpBarComm, SLOT(sayReady()));
			connect(this->m_ui->tableViewComm, SIGNAL(customContextMenuRequested(const QPoint&)),this, SLOT(tableViewComm_ContextMenu(const QPoint&)) );
			connect(this->m_ui->wUpBarComm, SIGNAL(updateClicked()), this, SLOT(refreshCommunicators()));

			this->m_ui->tableViewLoc->setContextMenuPolicy(Qt::CustomContextMenu);
			connect(this->m_ui->tableViewLoc, SIGNAL(updated()), this->m_ui->wUpBarLoc, SLOT(sayReady()));
			connect(this->m_ui->tableViewLoc, SIGNAL(customContextMenuRequested(const QPoint&)),this, SLOT(tableViewLoc_ContextMenu(const QPoint&)) );
			connect(this->m_ui->wUpBarLoc, SIGNAL(updateClicked()), this, SLOT(refreshLocations()));

			this->propMapper = new PropertiesMapper(this);
			this->propMapper->getMap().insert(_KEY_id, this->m_ui->lblUserID);
			this->propMapper->getMap().insert(_KEY_name, this->m_ui->lblUserName);

			connect(this->m_ui->wUpBarLoc, SIGNAL(updateClicked()), this, SLOT(refreshLocations()));

		 }

		virtual ~WidgetUser() {
			delete this->propMapper;
			delete this->m_ui;
		 }


	public slots:

		virtual void refreshAll() {
			this->m_ui->widgetProperties->refreshAll();
			refreshLocations();
			refreshCommunicators();
		 }

	protected slots:

		void refreshCommunicators() {
			postMessageForTarget( new Message(new Request(_UserManager_METHOD_listcomm)) );
			this->m_ui->wUpBarComm->sayRetrieving();
		 }

		void refreshLocations() {
			postMessageForTarget( new Message(new Request(_UserManager_METHOD_listloc)) );
			this->m_ui->wUpBarLoc->sayRetrieving();
		 }

	protected slots:

		void contextMenuLoc_triggered( QAction* selected ) {
			(void)selected;

		 }

		void contextMenuComm_triggered( QAction* selected ) {

Variant dataCommURI = this->m_ui->tableViewComm->getCurrentItemAsVariantAtCol(0);
Variant dataCommRank = this->m_ui->tableViewComm->getCurrentItemAsVariantAtCol(2);

			const double rankStep = 0.1;
			const double rankStepMin = 0.001;
			double rankCurr = dataCommRank.toDouble(0.0);
			Request* request_change = NULL;

			if ( selected == this->actionCommForce ) {
				NEW_List* dl = new NEW_List();
				dl->push_back<Variant>("CommunicatorForce");
				dl->push_back( dataCommURI.clone() );
				request_change = new Request( _METHOD_SetProperty, dl );
			 }
			else if ( selected == this->actionCommForceTs ) {
			 }
			else if ( selected == this->actionCommRankTop ) {
				double rankTmp = -10000000.0;
				for(unsigned int crow = 0; crow<this->m_ui->tableViewComm->getTableModel()->getDataTable()->getRows(); crow++) {
					const ISerializable* objCommRank = this->m_ui->tableViewComm->getTableModel()->getDataTable()->get(crow, 2);
					if ( objCommRank == NULL ) continue;
					if ( !objCommRank->isClass(_Variant_TYPE) ) continue;
					const Variant* dataCommRank = dynamic_cast<const Variant*>(objCommRank);
					if ( dataCommRank == NULL ) continue;
					if ( rankTmp < dataCommRank->toDouble(0.0) )
						rankTmp = dataCommRank->toDouble(0.0);
				 }
				NEW_List* dl = new NEW_List();
				dl->push_back( dataCommURI.clone() );
				dl->push_back<Variant>( rankTmp + rankStepMin );
				request_change = new Request( _UserManager_METHOD_rankcomm, dl );
			 }
			else if ( selected == this->actionCommRankUp ) {
				NEW_List* dl = new NEW_List();
				dl->push_back( dataCommURI.clone() );
				dl->push_back<Variant>( rankCurr + rankStep );
				request_change = new Request( _UserManager_METHOD_rankcomm, dl );
			 }
			else if ( selected == this->actionCommRankDown ) {
				NEW_List* dl = new NEW_List();
				dl->push_back( dataCommURI.clone() );
				dl->push_back<Variant>( rankCurr - rankStep );
				request_change = new Request( _UserManager_METHOD_rankcomm, dl );
			 }
			else if ( selected == this->actionCommRankBottom ) {
				double rankTmp = 10000000.0;
				for(unsigned int crow = 0; crow<this->m_ui->tableViewComm->getTableModel()->getDataTable()->getRows(); crow++) {
					const ISerializable* objCommRank = this->m_ui->tableViewComm->getTableModel()->getDataTable()->get(crow, 2);
					if ( objCommRank == NULL ) continue;
					if ( !objCommRank->isClass(_Variant_TYPE) ) continue;
					const Variant* dataCommRank = dynamic_cast<const Variant*>(objCommRank);
					if ( dataCommRank == NULL ) continue;
					if ( rankTmp > dataCommRank->toDouble(0.0) )
						rankTmp = dataCommRank->toDouble(0.0);
				 }
				NEW_List* dl = new NEW_List();
				dl->push_back( dataCommURI.clone() );
				dl->push_back<Variant>( rankTmp - rankStepMin );
				request_change = new Request( _UserManager_METHOD_rankcomm, dl );
			 }

//			else if ( selected == this->actionCommRemove )

			if ( request_change == NULL )
				return;
			postMessageForTarget( new Message(request_change) );
		 }

	protected slots:
		void tableViewComm_ContextMenu( const QPoint& pos ) {
			QPoint globalPos = this->mapToGlobal(pos);
			QAction* selected = this->menuComm->exec( globalPos );
			(void)selected;
		 }
		void tableViewLoc_ContextMenu( const QPoint& pos ) {
			QPoint globalPos = this->mapToGlobal(pos);
			QAction* selected = this->menuLoc->exec( globalPos );
			(void)selected;
		 }

	public:
		virtual QWidget* asQWidget()		{ return this; }

		virtual void busMessage( const Message& message, const Bus* ) {
			if ( !message.getContent()->isResponse() ) return;
			if ( !isMessageForMeOrFromTarget(message) )
				return;
			const wosh::Response* response = message.getContent()->asResponse();

			this->m_ui->tableViewComm->evalResponse(response);
			this->m_ui->tableViewLoc->evalResponse(response);

			if ( response->getMethod() == _UserManager_METHOD_rankcomm ) {
				QMessageBox::information(this, this->windowTitle(), tr("Communicator Ranking has been updated. Refreshing..") );
				refreshCommunicators();
				return;
			}

			this->propMapper->evalResponse(response);
		 }

		virtual void setTargetURI( const URI& uri ) {
			this->setWindowTitle( tr("User %1 [%2]").arg( uri.getName().c_str() ).arg( uri.toString().c_str() ) );
			IWidget::setTargetURI( uri );
			this->m_ui->widgetProperties->setTargetURI(uri);
			this->m_ui->lblRefURI->setText( QString(uri.toString().c_str()) );
		 }

	protected:
		void changeEvent(QEvent *e) {
			QWidget::changeEvent(e);
			switch (e->type()) {
				case QEvent::LanguageChange:
				m_ui->retranslateUi(this);
				break;
			default: break;
			}
		 }

	protected:
		void buildMenus() {

			this->actionCommForce = new QAction(this);
			this->actionCommForce->setText(tr("&Force Communicator (set as..)"));
			this->actionCommForceTs = new QAction(this);
			this->actionCommForceTs->setText(tr("&Force Timestamp (update)"));
			this->actionCommRankTop = new QAction(this);
			this->actionCommRankTop->setText(tr("Set &Top ranking"));
			this->actionCommRankUp = new QAction(this);
			this->actionCommRankUp->setText(tr("Set &Higher ranking"));
			this->actionCommRankDown = new QAction(this);
			this->actionCommRankDown->setText(tr("Set &Lower ranking"));
			this->actionCommRankBottom = new QAction(this);
			this->actionCommRankBottom->setText(tr("Set &Bottom ranking"));
			this->actionCommRemove = new QAction(this);
			this->actionCommRemove->setText(tr("&Remove Communicator"));

			this->menuComm = new QMenu(this);
			this->menuComm->addAction(this->actionCommForce);
			this->menuComm->addAction(this->actionCommForceTs);
			this->menuComm->addSeparator();
			this->menuComm->addAction(this->actionCommRankTop);
			this->menuComm->addAction(this->actionCommRankUp);
			this->menuComm->addAction(this->actionCommRankDown);
			this->menuComm->addAction(this->actionCommRankBottom);
			this->menuComm->addSeparator();
			this->menuComm->addAction(this->actionCommRemove);

			this->actionLocForceTs = new QAction(this);
			this->actionLocForceTs->setText(tr("&Force Timestamp (update)"));
			this->actionLocRankUp = new QAction(this);
			this->actionLocRankUp->setText(tr("Set &Higher ranking"));
			this->actionLocRankDown = new QAction(this);
			this->actionLocRankDown->setText(tr("Set &Lower ranking"));

			this->menuLoc = new QMenu(this);
			this->menuLoc->addAction(this->actionLocForceTs);
			this->menuLoc->addSeparator();
			this->menuLoc->addAction(this->actionLocRankUp);
			this->menuLoc->addAction(this->actionLocRankDown);

			connect(this->menuComm, SIGNAL(triggered(QAction*)),this, SLOT(contextMenuComm_triggered(QAction*)) );
			connect(this->menuLoc, SIGNAL(triggered(QAction*)),this, SLOT(contextMenuLoc_triggered(QAction*)) );

		 }

	protected:
		QMenu* menuComm;
		QAction* actionCommForce;
		QAction* actionCommForceTs;
		QAction* actionCommRankTop;
		QAction* actionCommRankUp;
		QAction* actionCommRankDown;
		QAction* actionCommRankBottom;
		QAction* actionCommRemove;

		QMenu* menuLoc;
		QAction* actionLocForceTs;
		QAction* actionLocRankUp;
		QAction* actionLocRankDown;

		PropertiesMapper* propMapper;

	private:
		Ui::WidgetUser *m_ui;


}; // class def

 }; // namespace gui
}; // namespace wosh


#endif //__WOSH_Gui_WidgetUser_H__
